package com.zhcx.zhcxlibrary.widget.dashboard;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.zhcx.zhcxlibrary.R;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;

/**
 * ProjectName: SmartBus
 * PackageName: com.zhcx.zhcxlibrary.widget.dashboard
 * description:
 * Date：2018/1/20 17:22
 * Author：Steven J
 * ClassName:ScaleView
 * Modify The Note:
 **/

public class ScaleView extends View {
    // 默认宽高值
    private int defaultSize;
    //外层圆环画笔
    private Paint mMiddleArcPaint;
    //进度圆环画笔
    private Paint mArcProgressPaint;

    private Context mContext;
    private RectF mMiddleRect;
    // view宽度
    private int width;
    // view高度
    private int height;
    //半径
    private int radius;
    // 默认Padding值
    private final static int defaultPadding = 20;
    //  圆环起始角度
    private final static float mStartAngle = 135f;

    // 圆环结束角度
    private final static float mEndAngle = 270f;
    //进度矩形
    private RectF mMiddleProgressRect;
    //内层矩形
    private RectF mInnerRect;
    //当前点的实际位置
    private float[] pos;

    //当前点的tangent值
    private float[] tan;
    //矩阵
    private Matrix matrix;
    //小圆点画笔
    private Paint mBitmapPaint;
    //小圆点
    private Bitmap bitmap;
    //小圆点
    private Bitmap kbitmap;
    // 当前进度
    private float mCurrentAngle = 0f;
    //总进度
    private float mTotalAngle = 270f;
    // 距离圆环的值
    private int arcDistance;
    //信用等级文本画笔
    private Paint mTextPaint;
    //大刻度画笔
    private Paint mCalibrationPaint;
    private Rect rect;
    private int planTrip;//计划车次
    private int sendTrip;//已完成车次
    private Paint mPaintCenter;
    private Paint mPaintBitmap;


    public ScaleView(Context context) {
        this(context, null);
    }

    public ScaleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScaleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    private void init() {
        rect = new Rect();
        defaultSize = DeviceUtils.dip2px(mContext, 220);
        arcDistance = DeviceUtils.dip2px(mContext, 14);
        //外层圆环画笔
        mMiddleArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mMiddleArcPaint.setStrokeWidth(DeviceUtils.dip2px(mContext, 5));
        mMiddleArcPaint.setColor(Color.WHITE);
        mMiddleArcPaint.setStyle(Paint.Style.STROKE);
        mMiddleArcPaint.setAlpha(80);
        mMiddleArcPaint.setStrokeCap(Paint.Cap.ROUND);
        mMiddleArcPaint.setAntiAlias(true);

        //外层进度画笔
        mArcProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mArcProgressPaint.setStrokeWidth(DeviceUtils.dip2px(mContext, 5));
        mArcProgressPaint.setColor(Color.WHITE);
        mArcProgressPaint.setStyle(Paint.Style.STROKE);
        mArcProgressPaint.setStrokeCap(Paint.Cap.ROUND);
        mArcProgressPaint.setAntiAlias(true);

        mBitmapPaint = new Paint();
        mBitmapPaint.setStyle(Paint.Style.FILL);
        mBitmapPaint.setAntiAlias(true);

        //初始化小圆点图片
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_circle);
        pos = new float[2];
        tan = new float[2];
        matrix = new Matrix();

        mPaintBitmap = new Paint();
        mPaintBitmap.setStyle(Paint.Style.FILL);
        mPaintBitmap.setAntiAlias(true);
        //初始化刻度图片
        kbitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_kbitmap);

        //正中间字体画笔
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setAntiAlias(true);

        //圆环大刻度画笔
        mCalibrationPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCalibrationPaint.setStrokeWidth(DeviceUtils.dip2px(mContext, 3));
        mCalibrationPaint.setStyle(Paint.Style.STROKE);
        mCalibrationPaint.setColor(Color.WHITE);
        mCalibrationPaint.setAlpha(80);
        mCalibrationPaint.setStrokeCap(Paint.Cap.ROUND);
        mCalibrationPaint.setAntiAlias(true);

        mPaintCenter = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintCenter.setStrokeWidth(DeviceUtils.dip2px(mContext, 5));
        mPaintCenter.setColor(Color.WHITE);
        mPaintCenter.setStyle(Paint.Style.STROKE);
        mPaintCenter.setAlpha(80);
        mPaintCenter.setStrokeCap(Paint.Cap.ROUND);
        mPaintCenter.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawMiddleArc(canvas);
        drawRingProgress(canvas);
        drawCenterText(canvas);
        drawCalibrationAndText(canvas);
//        drawCenterCircle(canvas);
    }

    private void drawCenterCircle(Canvas canvas) {
        canvas.drawCircle(width / 2, height / 2, (height / 2) - 10, mPaintCenter);
    }

    /**
     * 绘制外层圆环
     */
    private void drawMiddleArc(Canvas canvas) {
        canvas.drawArc(mMiddleRect, mStartAngle, mEndAngle, false, mMiddleArcPaint);
//        canvas.drawRect(mMiddleRect, mMiddleArcPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(resolveMeasure(widthMeasureSpec, defaultSize),
                resolveMeasure(heightMeasureSpec, defaultSize));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        super.onSizeChanged(w, h, oldw, oldh);

        width = w;
        height = h;
        radius = width / 2;

        mMiddleRect = new RectF(
                defaultPadding, defaultPadding,
                width - defaultPadding, height - defaultPadding);

        mMiddleProgressRect = new RectF(
                defaultPadding, defaultPadding,
                width - defaultPadding, height - defaultPadding);
    }

    /**
     * 根据传入的值进行测量
     */
    public int resolveMeasure(int measureSpec, int defaultSize) {

        int result = 0;
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (MeasureSpec.getMode(measureSpec)) {

            case MeasureSpec.UNSPECIFIED:
                result = defaultSize;
                break;

            case MeasureSpec.AT_MOST:
                //设置warp_content时设置默认值
                result = Math.min(specSize, defaultSize);
                break;
            case MeasureSpec.EXACTLY:
                //设置math_parent 和设置了固定宽高值
                break;

            default:
                result = defaultSize;
        }

        return result;
    }

    /**
     * 绘制外层圆环进度和小圆点
     */
    private void drawRingProgress(Canvas canvas) {
        Path path = new Path();
        path.addArc(mMiddleProgressRect, mStartAngle, mCurrentAngle);
        PathMeasure pathMeasure = new PathMeasure(path, false);
        pathMeasure.getPosTan(pathMeasure.getLength() * 1, pos, tan);
        matrix.reset();
        matrix.postTranslate(pos[0] - bitmap.getWidth() / 2, pos[1] - bitmap.getHeight() / 2);
        canvas.drawPath(path, mArcProgressPaint);
        //起始角度不为0时候才进行绘制小圆点
        if (mCurrentAngle == 0) {
            return;
        }
        canvas.drawBitmap(bitmap, matrix, mBitmapPaint);
        mBitmapPaint.setColor(Color.WHITE);
        canvas.drawCircle(pos[0], pos[1], 10, mBitmapPaint);
    }

    public void startAnim() {
        ValueAnimator mAngleAnim = ValueAnimator.ofFloat(mCurrentAngle, mTotalAngle);
        mAngleAnim.setInterpolator(new AccelerateDecelerateInterpolator());
        mAngleAnim.setDuration(500);
        mAngleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {

                mCurrentAngle = (float) valueAnimator.getAnimatedValue();
                postInvalidate();
            }
        });
        mAngleAnim.start();
    }

    /**
     * 绘制中间文本
     */
    private void drawCenterText(Canvas canvas) {

        //绘制信用分数
        mTextPaint.setTextSize(DeviceUtils.dip2px(mContext, 24));
        mTextPaint.setFakeBoldText(false); //true为粗体，false为非粗体
        mTextPaint.setStyle(Paint.Style.STROKE);
        mTextPaint.getTextBounds("完", 0, 1, rect);
        if (planTrip == 0) {
            canvas.drawText("暂无数据", radius, radius, mTextPaint);
        } else {
            canvas.drawText("已完成", radius, radius, mTextPaint);
            mTextPaint.setTextSize(DeviceUtils.dip2px(mContext, 22));
            mTextPaint.setFakeBoldText(true); //true为粗体，false为非粗体
            mTextPaint.setStyle(Paint.Style.STROKE);
            canvas.drawText(sendTrip + "次", radius, radius + rect.height(), mTextPaint);

            mTextPaint.setTextSize(DeviceUtils.dip2px(mContext, 17));
            mTextPaint.setFakeBoldText(false); //true为粗体，false为非粗体
            mTextPaint.setStyle(Paint.Style.STROKE);
            canvas.drawText("计划车次" + planTrip + "次", radius, (height - (defaultPadding * 3)), mTextPaint);
        }
    }

    /**
     * 绘制刻度
     */
    private void drawCalibrationAndText(Canvas canvas) {
        //旋转画布进行绘制对应的刻度
        canvas.save();
        canvas.rotate(mStartAngle * (-1), radius, radius);
        //计算刻度线的起点结束点
        int startDst = (int) (defaultPadding + arcDistance - 30 / 2 - 1);
        int endDst = (int) (startDst + 8);
        //刻度旋转的角度
        int rotateAngle = 270 / 10;
        //计算圆弧的长度
        float arclength = (float) (radius * (180 / 2) * Math.PI / 180);
//        LogUtils.e(arclength);
        for (int i = 0; i < 11; i++) {
//            if (i % 2 != 0) {
            canvas.drawLine(radius, startDst, radius, endDst, mCalibrationPaint);
//            canvas.drawBitmap(kbitmap, radius, startDst, mBitmapPaint);
//            }
            // 测量文本的长度
            canvas.rotate(rotateAngle, radius, radius);
        }
        canvas.restore();
    }

    public void setStatusTextPlan(int sendtrip, int plantrip, String status) {
        this.planTrip = plantrip;
        this.sendTrip = sendtrip;
        if (plantrip != 0) {
            //比例
            float a = (270f / planTrip);
            mTotalAngle = sendtrip * a;
            startAnim();
        }else {
            mTotalAngle=0;
            startAnim();
        }
    }
}
